import { ENV } from '@server/env'
import { Request } from 'express'
import { UnauthorizedError } from '@server/error/errors'
import jwt from 'jsonwebtoken'
import { customUserInfo, getUserInfo } from './user-info'

export function checkUserInfo(request: Request) {
  const token = (request.headers['authorization'] || request.headers['Authorization'] || '') as string
  if (!token) {
    return customUserInfo
  }

  if (!token.startsWith('JWT ')) {
    throw new UnauthorizedError('Invalid Authorization Header')
  }

  try {
    const decoded = jwt.verify(token.slice(4), ENV.JWT_SECRET)
    if (typeof decoded === 'string') {
      throw new UnauthorizedError(decoded)
    }
    const userId = decoded.userId
    if (!userId) {
      throw new UnauthorizedError('Invalid JWT')
    }
    return getUserInfo(userId)
  } catch (err) {
    throw new UnauthorizedError(err instanceof Error ? err.message : 'Not Authorized')
  }
}
